package com.mj.mafeed.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.mj.mafeed.R;
import com.mj.mafeed.activity.ForumTopicActivity;
import com.mj.mafeed.activity.ForumTopicDetailActivity;
import com.mj.mafeed.bean.ForumTopicJSON;
import com.mj.mafeed.bean.ForumTopicJSON.ForumTopicImage;
import com.mj.mafeed.bean.MemberJSON;
import com.mj.mafeed.service.ForumTopicService;
import com.mj.mafeed.util.DateUtils;
import com.mj.mafeed.util.HttpUtils;
import com.mj.mafeed.util.NetUtils;
import com.mj.mafeed.widget.LoadingDialog;
import com.mj.mafeed.widget.MyGridView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;

/**
 * 资讯
 * @author zhaominglei
 * @date 2016-1-29
 * 
 */
public class ForumTopicAdapter extends BaseAdapter{
	public static final int MAX_FORUM_REPLY_COUNT = 2; //最大显示评论条数
	private ForumTopicService forumTopicService = new ForumTopicService();
	private Context context;
	private ForumTopicActivity forumTopicActivity;
	private List<ForumTopicJSON> forumTopics;
	private ImageLoader imageLoader = null;
	@SuppressWarnings("unused")
	private DisplayImageOptions options = null;
	private MyGridView gridView; //图片视图
	private Bitmap bitmap; //导入图片
	private ArrayList<HashMap<String, Object>> imageItem;
	private SimpleAdapter simpleAdapter;
	private String username; //用户名
	private String sign; //签名
	private LoadingDialog loadingDialog; //加载框
	private Dialog dialog; //评论对话框
	private EditText commentContentEdt; //评论
	private Button sendBtn; //发送
	private Intent intent;
	
	@SuppressWarnings("deprecation")
	public ForumTopicAdapter(Context context, List<ForumTopicJSON> forumTopics, String username, String sign) {
		super();
		this.forumTopics = forumTopics;
		this.context = context;
		this.forumTopicActivity = (ForumTopicActivity)context;
		this.username = username;
		this.sign = sign;
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(context));

		options = new DisplayImageOptions.Builder()
				.displayer(new RoundedBitmapDisplayer(0xff000000, 10))
				.cacheInMemory().cacheOnDisc().build();
	}

	public List<ForumTopicJSON> getForumTopics() {
		return forumTopics;
	}

	public void setForumTopics(List<ForumTopicJSON> forumTopics) {
		this.forumTopics.clear();
		this.forumTopics.addAll(forumTopics);
	}

	@Override
	public int getCount() {
		return forumTopics.size();
	}

	@Override
	public Object getItem(int position) {
		return forumTopics.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressLint("ViewHolder")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
//		RelativeLayout relativeLayout;
//		if (convertView != null) {
//			relativeLayout = (RelativeLayout) convertView;
//		} else {
//			relativeLayout = (RelativeLayout) View.inflate(context, R.layout.forumtopic_item, null);
//		}
		RelativeLayout relativeLayout = (RelativeLayout) View.inflate(context, R.layout.forumtopic_item, null);
		@SuppressWarnings("unused")
		ProgressBar progressBar = (ProgressBar)relativeLayout.findViewById(R.id.forumtopic_item_progress);
		ImageView headpic = (ImageView)relativeLayout.findViewById(R.id.forumtopic_item_headpic);
		TextView forumtopicUsername = (TextView)relativeLayout.findViewById(R.id.forumtopic_item_username);
		TextView forumtopicCreatedate = (TextView)relativeLayout.findViewById(R.id.forumtopic_item_createdate);
		TextView forumtopicContent = (TextView)relativeLayout.findViewById(R.id.forumtopic_item_content);
		TextView forumtopicPraises = (TextView)relativeLayout.findViewById(R.id.forumtopic_item_praises);
		TextView forumtopicReplies = (TextView)relativeLayout.findViewById(R.id.forumtopic_item_replies);
		ImageView forumtopicPraise = (ImageView)relativeLayout.findViewById(R.id.forumtopic_item_praise);
		ImageView forumtopicReply = (ImageView)relativeLayout.findViewById(R.id.forumtopic_item_reply);
		RelativeLayout forumtopicRelative3 = (RelativeLayout)relativeLayout.findViewById(R.id.forumtopic_item_relative3);
		TextView forumtopicRepliesMore = (TextView)relativeLayout.findViewById(R.id.forumtopic_item_replies_more);
		loadingDialog = new LoadingDialog(parent.getContext());
		
		gridView = (MyGridView)relativeLayout.findViewById(R.id.forumtopic_item_gridView);
		final ForumTopicJSON forumTopicJSON = forumTopics.get(position);
		headpic.setBackgroundResource(R.drawable.user_icon);
		forumtopicUsername.setText(forumTopicJSON.getMemberJSON().getUsername());
		forumtopicCreatedate.setText(DateUtils.getDateTime(DateUtils.datePattern, forumTopicJSON.getCreateDate()));
		forumtopicContent.setText(forumTopicJSON.getContent());
		List<ForumTopicJSON.ForumTopicImage> forumTopicImages = forumTopicJSON.getForumTopicImages();
		if (forumTopicImages != null && !forumTopicImages.isEmpty()) {
			imageItem = new ArrayList<HashMap<String,Object>>();
			for (ForumTopicImage forumTopicImage : forumTopicImages) {
				if (forumTopicImage.getSource() == null || forumTopicImage.getSource().equals("")) continue;
				bitmap = HttpUtils.returnBitMap(forumTopicImage.getSource());
				HashMap<String,Object> map = new HashMap<String, Object>();
				map.put("itemImage", bitmap);
				imageItem.add(map);
				simpleAdapter = new SimpleAdapter(context, imageItem, R.layout.griditem_addpic, new String[]{ "itemImage" }, new int[]{ R.id.griditem_addpic });
				simpleAdapter.setViewBinder(new ViewBinder() {
					@Override
					public boolean setViewValue(View view, Object data,
							String textRepresentation) {
						if (view instanceof ImageView && data instanceof Bitmap) {
							ImageView imageView = (ImageView)view;
							imageView.setImageBitmap((Bitmap)data);
							return true;
						}
						return false;
					}
				});
				gridView.setAdapter(simpleAdapter);
			}
		}
		if (forumTopicJSON.getForumTopicPraises() != null && !forumTopicJSON.getForumTopicPraises().isEmpty()) {
			forumtopicPraises.setText(forumTopicJSON.getForumTopicPraises().size()+"次赞");
			for (ForumTopicJSON.ForumTopicPraise forumTopicPraise : forumTopicJSON.getForumTopicPraises()) {
				MemberJSON memberJSON = forumTopicPraise.getMemberJSON();
				if (memberJSON != null && username != null && username.equals(memberJSON.getUsername())) {
					forumtopicPraise.setImageResource(R.drawable.news_liked);
				}
			}
		}
		if (forumTopicJSON.getReplyCount() != null && forumTopicJSON.getReplyCount().intValue() > 0) {
			forumtopicReplies.setText(forumTopicJSON.getReplyCount()+"次评论");
		}
		if (forumTopicJSON.getForumReplies() != null && !forumTopicJSON.getForumReplies().isEmpty()) {
			for (int i = 0; i < forumTopicJSON.getForumReplies().size(); i++) {
				if (i == MAX_FORUM_REPLY_COUNT) break;
				ForumTopicJSON.ForumReply forumReply = forumTopicJSON.getForumReplies().get(i);
				TextView forumReplyMember = new TextView(context);
				forumReplyMember.setTextColor(context.getResources().getColor(R.color.forumReplyMember_color));
				forumReplyMember.setText(forumReply.getMemberJSON().getName()+":");
				forumReplyMember.setId((i*2+1));
				TextView forumReplyContent = new TextView(context);
				forumReplyContent.setTextColor(context.getResources().getColor(R.color.black));
				forumReplyContent.setText(forumReply.getContent());
				
				RelativeLayout.LayoutParams layoutParams0 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
				if (i > 0) {
					layoutParams0.addRule(RelativeLayout.BELOW, (i*2-1));
				}
				forumtopicRelative3.addView(forumReplyMember, layoutParams0);
				RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
				if (i > 0) {
					layoutParams1.addRule(RelativeLayout.BELOW, (i*2-1));
				}
				layoutParams1.addRule(RelativeLayout.RIGHT_OF, (i*2+1));
				forumtopicRelative3.addView(forumReplyContent, layoutParams1);
			}
			forumtopicRepliesMore.setVisibility(View.VISIBLE);
		} else {
			forumtopicRepliesMore.setVisibility(View.GONE);
		}
		
		forumtopicPraise.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (forumTopicJSON != null) {
					if (username != null && !username.equals("") && sign != null && !sign.equals("")) {
						forumtopicPraise(v, forumTopicJSON);
					} else {
						Toast.makeText(context, R.string.check_login_error, Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		forumtopicReply.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (forumTopicJSON != null) {
					if (username != null && !username.equals("") && sign != null && !sign.equals("")) {
						showDialogBottom(v, forumTopicJSON);
					} else {
						Toast.makeText(context, R.string.check_login_error, Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		forumtopicRepliesMore.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (forumTopicJSON != null) {
					intent = new Intent(forumTopicActivity, ForumTopicDetailActivity.class);
					intent.putExtra("referer", "ForumTopicActivity");
					Bundle bundle = new Bundle();
					bundle.putSerializable("forumTopicJSON", forumTopicJSON);
					intent.putExtras(bundle);
					forumTopicActivity.startActivity(intent);
				}
			}
		});
		return relativeLayout;
	}
	
	private void forumtopicPraise(View v, ForumTopicJSON forumTopicJSON) {
		if (NetUtils.isConnected(context)) {
			loadingDialog.show();
			new ForumTopicPraiseAsyncTask().execute(forumTopicJSON.getForumTopicId().toString());
		} else {
			Toast.makeText(context, R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	@SuppressLint("InflateParams")
	private void showDialogBottom(View v,final ForumTopicJSON forumTopicJSON) {
		dialog = new Dialog(context);
		LayoutInflater inflater = forumTopicActivity.getLayoutInflater();
		View dialogView = inflater.inflate(R.layout.dialog_comment, null);
		commentContentEdt = (EditText)dialogView.findViewById(R.id.dialog_comment_content);
		sendBtn = (Button)dialogView.findViewById(R.id.dialog_comment_send); //评论发送
		
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(dialogView);
		Window window = dialog.getWindow();  
	    window.setGravity(Gravity.BOTTOM);  //设置dialog显示的位置  
	    window.setWindowAnimations(R.style.dialogBottom); //添加动画
	    dialog.show();
	    Display display = forumTopicActivity.getWindowManager().getDefaultDisplay();
	    WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = (int) (display.getWidth());
	    dialog.getWindow().setAttributes(layoutParams);
	    
	    sendBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String content = commentContentEdt.getText().toString();
				if (content == null || content.equals("")) {
					Toast.makeText(context, R.string.dialog_comment_content_hint, Toast.LENGTH_SHORT).show();
					return;
				}
				if (forumTopicJSON != null) {
					if (username != null && !username.equals("") && sign != null && !sign.equals("")) {
						forumtopicComment(v, forumTopicJSON, content);
						dialog.dismiss();
						commentContentEdt.setText("");
					} else {
						Toast.makeText(context, R.string.check_login_error, Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
	}

	private void forumtopicComment(View v, ForumTopicJSON forumTopicJSON, String content) {
		if (NetUtils.isConnected(context)) {
			loadingDialog.show();
			new ForumTopicCommentAsyncTask().execute(forumTopicJSON.getForumTopicId().toString(), content);
		} else {
			Toast.makeText(context, R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}

	public class ForumTopicPraiseAsyncTask extends AsyncTask<String, String, ForumTopicJSON> {
		@Override
		protected ForumTopicJSON doInBackground(String... params) {
			return forumTopicService.praise("ForumTopicActivity", params[0], username, sign);
		}
		@Override
		protected void onPostExecute(ForumTopicJSON result) {
			loadingDialog.dismiss();
			if (result != null) {
				//重置forumTopics中对应值
				List<ForumTopicJSON> forumTopicList = new ArrayList<ForumTopicJSON>();
				List<ForumTopicJSON> forumTopics = forumTopicActivity.forumTopicAdapter.getForumTopics();
				for (int i = 0; i < forumTopics.size(); i++) {
					ForumTopicJSON forumTopicJSON = forumTopics.get(i);
					if (forumTopicJSON.getForumTopicId().equals(result.getForumTopicId())) {
						forumTopicList.add(result);
						continue;
					}
					forumTopicList.add(forumTopicJSON);
				}
				forumTopicActivity.forumTopicAdapter.setForumTopics(forumTopicList);
				forumTopicActivity.forumTopicAdapter.notifyDataSetChanged();
				forumTopicActivity.onLoad();
				Toast.makeText(context, R.string.praise_success, Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(context, R.string.praise_error, Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public class ForumTopicCommentAsyncTask extends AsyncTask<String, String, ForumTopicJSON> {
		@Override
		protected ForumTopicJSON doInBackground(String... params) {
			return forumTopicService.comment("ForumTopicActivity", params[0], params[1], username, sign);
		}

		@Override
		protected void onPostExecute(ForumTopicJSON result) {
			loadingDialog.dismiss();
			if (result != null) {
				//重置forumTopics中对应值
				List<ForumTopicJSON> forumTopicList = new ArrayList<ForumTopicJSON>();
				List<ForumTopicJSON> forumTopics = forumTopicActivity.forumTopicAdapter.getForumTopics();
				for (int i = 0; i < forumTopics.size(); i++) {
					ForumTopicJSON forumTopicJSON = forumTopics.get(i);
					if (forumTopicJSON.getForumTopicId().equals(result.getForumTopicId())) {
						forumTopicList.add(result);
						continue;
					}
					forumTopicList.add(forumTopicJSON);
				}
				forumTopicActivity.forumTopicAdapter.setForumTopics(forumTopicList);
				forumTopicActivity.forumTopicAdapter.notifyDataSetChanged();
				forumTopicActivity.onLoad();
				Toast.makeText(context, R.string.comment_success, Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(context, R.string.comment_error, Toast.LENGTH_SHORT).show();
			}
		}
	}
}
